<template>
  <div :class="classes" ref="tagsWarp">
    <!-- <div :class="[prefixCls + '-nav-prev']" @click="scrollPrev">
      <Icon type="ios-arrow-back"></Icon>
    </div> -->
    <div
      ref="navScroll"
      :class="[prefixCls + '-nav-scroll']"
      @DOMMouseScroll="handleScroll"
      @mousewheel="handleScroll"
    >
      <div :class="[prefixCls + '-nav']" ref="nav" :style="navStyle">
        <template v-for="(item, index) in getTag">
          <div v-if="item.path !== '/'" :key="index" :class="tabCls(item)">
            <div class="close" @click="handleCloseTag(item.path)">
              <Icon type="md-close" />
            </div>
            <div class="title" @click="handleSelecteTag(item.path)">
              <Dropdown
                trigger="contextMenu"
                transfer
                @on-click="handleDropdown"
              >
                <span>
                  {{ item.title }}
                </span>
                <DropdownMenu slot="list">
                  <DropdownItem name="left"
                    ><Icon type="ios-arrow-round-back" />关闭左侧</DropdownItem
                  >
                  <DropdownItem name="right"
                    ><Icon
                      type="ios-arrow-round-forward"
                    />关闭右侧</DropdownItem
                  >
                  <DropdownItem nmae="other"
                    ><Icon type="ios-close" />关闭其它</DropdownItem
                  >
                  <DropdownItem name="all"
                    ><Icon
                      type="ios-close-circle-outline"
                    />全部关闭</DropdownItem
                  >
                </DropdownMenu>
              </Dropdown>
            </div>
          </div>
        </template>
      </div>
    </div>
    <!-- <div :class="[prefixCls + '-nav-next']" @click="scrollNext">
      <Icon type="ios-arrow-forward"></Icon>
    </div> -->
  </div>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
const prefixCls = "yui-tags";
export default {
  name: "TagsView",
  data() {
    return {
      prefixCls: prefixCls,
      activeTagsName: "",
      tagsWidth: 120,
      navStyle: {
        transform: ""
      }
    };
  },
  computed: {
    ...mapGetters({
      getTag: "tagsView/getTag"
    }),
    classes() {
      return [`${prefixCls}`];
    }
  },
  watch: {
    $route() {
      this.handleRouteChange();
    }
  },
  created() {
    this.activeTagsName = this.$route.path;
  },
  methods: {
    ...mapActions({
      addTag: "tagsView/addTag",
      delTag: "tagsView/delTag"
    }),
    handleRouteChange() {
      this.activeTagsName = this.$route.path;
      this.addTag(this.$route);
      this.$nextTick(() => {
        this.scrollToActiveTab();
      });
    },
    // 标签选择时触发
    handleSelecteTag(path) {
      const rs = this.getTag.filter(item => {
        return path === item.path;
      })[0];
      if (path !== this.$route.path) {
        this.$router.push({ path: path, query: rs.query, params: rs.params });
      }
    },
    //标签关闭时触发
    handleCloseTag(path) {
      this.delTag(path).then(response => {
        // 只有在关闭当前打开的标签页才会有影响
        let lastView;
        if (response.tagIndex === response.visitedTag.length) {
          lastView = response.visitedTag.slice(-1)[0]; // 选取路由数组中的最后一位
        } else {
          lastView = response.visitedTag.slice(response.tagIndex)[0]; // 选取路由数组中的最后一位
        }
        if (lastView) {
          this.$router.push({ path: lastView.path });
        } else {
          this.$router.push({ path: "/" });
        }
      });
    },
    tabCls(item) {
      return [
        `${prefixCls}-tab`,
        {
          [`${prefixCls}-tab-active`]: item.path === this.activeTagsName
        }
      ];
    },
    handleScroll(e) {
      e.preventDefault();
      e.stopPropagation();
      const type = e.type;
      let delta = 0;
      if (type === "DOMMouseScroll" || type === "mousewheel") {
        delta = e.wheelDelta ? e.wheelDelta : -(e.detail || 0) * 40;
      }
      if (delta > 0) {
        this.scrollPrev();
      } else {
        this.scrollNext();
      }
    },
    scrollPrev() {
      const containerWidth = this.$refs.navScroll.offsetWidth;
      const currentOffset = this.getCurrentScrollOffset();
      if (!currentOffset) return;
      let newOffset =
        currentOffset > containerWidth ? currentOffset - containerWidth : 0;
      this.setOffset(newOffset);
    },
    scrollNext() {
      const navWidth = this.$refs.nav.offsetWidth;
      const containerWidth = this.$refs.navScroll.offsetWidth;
      const currentOffset = this.getCurrentScrollOffset();
      if (navWidth - currentOffset <= containerWidth) return;
      let newOffset =
        navWidth - currentOffset > containerWidth * 2
          ? currentOffset + containerWidth
          : navWidth - containerWidth;
      this.setOffset(newOffset);
    },
    getCurrentScrollOffset() {
      const { navStyle } = this;
      return navStyle.transform
        ? Number(navStyle.transform.match(/translateX\(-(\d+(\.\d+)*)px\)/)[1])
        : 0;
    },
    setOffset(value) {
      this.navStyle.transform = `translateX(-${value}px)`;
    },
    scrollToActiveTab() {
      // if (!this.scrollable) return;

      const nav = this.$refs.nav;
      const activeTab = this.$el.querySelector(`.${prefixCls}-tab-active`);
      if (!activeTab) return;
      const navScroll = this.$refs.navScroll;
      const activeTabBounding = activeTab.getBoundingClientRect();
      const navScrollBounding = navScroll.getBoundingClientRect();
      const navBounding = nav.getBoundingClientRect();
      const currentOffset = this.getCurrentScrollOffset();
      let newOffset = currentOffset;
      if (navBounding.right < navScrollBounding.right) {
        newOffset = nav.offsetWidth - navScrollBounding.width;
      }
      if (activeTabBounding.right > navScrollBounding.right) {
        newOffset =
          currentOffset + activeTabBounding.right - navScrollBounding.right;
      } else if (activeTabBounding.left < navScrollBounding.left) {
        // newOffset = navScrollBounding.left;
        newOffset =
          currentOffset + (activeTabBounding.left - navScrollBounding.left);
      }
      if (currentOffset !== newOffset) {
        this.setOffset(Math.max(newOffset, 0));
      }
    },
    handleDropdown(name) {
      switch (name) {
        case "left":
          break;
        case "right":
          break;

        case "other":
          break;

        case "all":
          this.getTag.forEach(item => {
            this.delTag(item.path);
          });
          break;
      }
    }
  }
};
</script>
<style lang="scss" scoped></style>
